package org.daochong.fastdev;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.daochong.lang.BeanUtil;
import org.daochong.lang.JdbcTemplate;
import org.daochong.lang.Page;
import org.daochong.lang.PageResult;

public class DefaultJpaOperations implements JpaOperations {
	private JdbcTemplate jdbc;

	public JdbcTemplate getJdbc() {
		return jdbc;
	}

	public void setJdbc(JdbcTemplate jdbc) {
		this.jdbc = jdbc;
	}

	protected JdbcTemplate jdbc() {
		return jdbc;
	}

	public boolean create(Object o, Map<String, Object> extData) throws SQLException {
		return jdbc().create(o, extData);
	}

	public boolean createBySql(String sqlId, Map<String, Object> params) throws SQLException {
		JdbcTemplate jdbc = jdbc();
		return jdbc.execute(sqlId, params) > 0;
	}

	public boolean update(Object o, Map<String, Object> extData) throws SQLException {
		return jdbc().update(o, extData);
	}

	public boolean updateBySql(String sqlId, Map<String, Object> params) throws SQLException {
		return jdbc().execute(sqlId, params) > 0;
	}

	public boolean updateWithoutNull(Object o, Map<String, Object> extData) throws SQLException {
		return jdbc().updateWithoutNull(o, extData);
	}

	public boolean delete(Object o) throws SQLException {
		return jdbc().delete(o);
	}

	public boolean deleteBySql(String sqlId, Map<String, Object> params) throws SQLException {
		return jdbc().execute(sqlId, params) > 0;
	}

	public boolean exists(Object o) throws SQLException {
		return jdbc().isExists(o);
	}

	public boolean existsBySql(String sqlId, Map<String, Object> params) throws SQLException {
		return jdbc().firstMap(sqlId, params) != null;
	}

	public Object load(Object o) throws SQLException {
		return jdbc().load(o);
	}

	public Object loadBySql(Class<?> clazz, String sqlId, Map<String, Object> params) throws SQLException {
		return jdbc().first(sqlId, clazz, params);
	}

	public boolean save(Object o, Map<String, Object> extData) throws SQLException {
		return jdbc().save(o, extData);
	}

	public boolean saveBySql(String sqlId, Map<String, Object> params) throws SQLException {
		return jdbc().execute(sqlId, params) > 0;
	}

	public List<?> list(Class<?> clazz) throws SQLException {
		return jdbc().list("select * from " + BeanUtil.getOrmInfo(clazz).getTableName(), clazz);
	}

	public List<?> listBySql(String sqlId, Class<?> clazz, Map<String, Object> params) throws SQLException {
		return jdbc().list(sqlId, clazz, params);
	}

	public PageResult<?> page(Page page, Class<?> clazz) throws SQLException {
		return jdbc().list(page, "select * from " + BeanUtil.getOrmInfo(clazz).getTableName(), clazz);
	}

	public PageResult<?> pageBySql(Page page, String sqlId, Class<?> clazz, Map<String, Object> params)
			throws SQLException {
		return jdbc().list(page, sqlId, clazz, params);
	}

}
